<template>
    <div class="btn-import-group" v-if="importProgram == 0">
        <v-btn style="width: 100%; margin: 10px" @click="importProgram = 1">手工导入单词</v-btn>
        <v-btn style="width: 100%; margin: 10px" @click="importProgram = 2">文件解析导入单词</v-btn>
    </div>
    <v-btn @click="clearProgram" v-if="importProgram >= 1">返回上一步</v-btn>
    <br /><br />
    <v-divider />
    <br />
    <v-card v-if="importProgram >= 1">
        <v-card-title class="text-h5">
            {{ programTitle[importProgram] }}
        </v-card-title>
        <v-row>
            <v-col cols="12" md="4">
                <v-combobox v-model="langId" label="选择语种（必选项）" :items="langList" item-title="lang"
                    item-value="langId"></v-combobox>
            </v-col>
            <v-col cols="12" md="4">
                <v-select v-model="selectedBookList" clearable label="同时添加到字典（可选项）" multiple item-title="title"
                    item-value="id" :items="bookList" variant="outlined" />
            </v-col>
            <v-col cols="12" md="4">
                <v-select clearable chips label="同时添加到标签（可选项）" item-title="name" item-value="id" :items="labelList"
                    v-model="selectedLabelList" multiple variant="outlined" />
            </v-col>
            <div style="display: flex; padding: 0 10px;width:100%">
                <v-checkbox v-model="pronunciationTTSCheckbox" label="生成音标发音" value="pronunciationTTS"></v-checkbox>
                <v-checkbox v-model="meanSelfTTSCheckbox" label="生成meanSelf解释发音" value="meanSelfTTS"></v-checkbox>
                <v-text-field v-model="meanSelfVoiceName" v-if="meanSelfTTSCheckbox" label="meanSelf VoiceName"></v-text-field>
                <v-checkbox v-model="meanLocalTTSCheckbox" label="生成meanLocal解释发音" value="meanLocalTTS"></v-checkbox>
                <v-text-field v-model="meanLocalVoiceName" v-if="meanLocalTTSCheckbox" label="meanLocal VoiceName"></v-text-field>
                <v-radio-group inline v-model="refreshWord">
                    <v-radio label="不刷新" value="none"></v-radio>
                    <v-radio label="从缓存刷新" value="refreshFromCache"></v-radio>
                    <v-radio label="从网络刷新" value="refreshFromInternet"></v-radio>
                </v-radio-group>
            </div>
        </v-row>
        <div v-if="importProgram == 1">
            <v-card-text>请在下方输入要导入的单词，支持“，”、“,”、“；”、“;”以及换行分割符</v-card-text>
            <v-textarea v-model.trim="inputText" hint="example：abandon，ahead，about，...." />
            <v-btn style="width: 100%" @click="inputParse">解析</v-btn>
        </div>
        <div v-if="importProgram == 2">
            <v-row>
                <v-col cols="12" md="7">
                    <v-file-input accept=".txt,.text" @update:model-value="selectFileListener" show-size clearable
                        label="选择文本文件" />
                </v-col>
                <v-col cols="12" md="2">
                    <v-combobox v-model="selectedSplitFlag" clearable label="选择分隔符" :items="splitFlag"
                        item-title="title" item-value="id"></v-combobox>
                </v-col>
                <v-col cols="12" md="2">
                    <v-combobox v-model="selectedReplaceFlag" clearable label="选择换行符" :items="replaceFlag"
                        item-title="title" item-value="id"></v-combobox>
                </v-col>
                <v-col cols="12" md="1">
                    <v-btn style="width: 100%" @click="fileParse">解析</v-btn>
                </v-col>
            </v-row>
        </div>
        <p style="padding: 0 10px;margin-top: 20px;" v-if="importWordList != null && importWordList.length > 0">
            总共 <strong>{{ importWordList.length }}</strong> 个单词
        </p>
        <div class="grid-container" style="max-height: 300px;">
            <div v-for="(word, index) in importWordList" v-bind:key="index" class="grid-item">
                {{ word }}
            </div>
        </div>
    </v-card>
    <v-overlay :model-value="overlay" class="align-center justify-center">
        <v-progress-circular color="primary" indeterminate size="64"></v-progress-circular>
    </v-overlay>
</template>

<script>
import { adminBathImportPresetWord } from '@/api/adminWord';

export default {
    name: "ImportWordComponent",
    props: {
        langList: { default: [] },
        labelList: { default: [] },
        bookList: { default: [] },
        sendSnackbarMessage: Function,
        importResponseCallback: Function
    },
    data() {
        return {
            overlay: false,
            importProgram: 0,
            programTitle: ["", "手工导入单词", "文件解析导入单词"],
            langId: undefined,
            pronunciationTTSCheckbox: false,
            meanSelfTTSCheckbox: false,
            meanLocalTTSCheckbox: false,
            meanLocalVoiceName:null,
            meanSelfVoiceName:null,
            refreshWord:'none',
            selectedBookList: [],
            selectedLabelList: [],
            splitFlag: [
                { id: 1, title: "换行", flag: "\n" },
                { id: 2, title: "空格", flag: " " },
                { id: 3, title: "空字符", flag: "" },
            ],
            selectedSplitFlag: undefined,
            replaceFlag: [
                { id: 1, title: "换行", flag: "\n" },
                { id: 2, title: "空格", flag: " " },
                { id: 3, title: "空字符", flag: "" },
            ],
            selectedReplaceFlag: undefined,
            importWordList: [],
            wordTextFile: undefined,
            inputText: undefined,
        };
    },
    methods: {
        startTask() {
            this.overlay = true
            setTimeout(() => {
                this.overlay = false
            }, 10000);
            if (this.importWordList == null || this.importWordList.length == 0) {
                this.overlay = false
                return;
            }
            if (this.langId == undefined) {
                this.overlay = false
                return
            }
            let taskPackage = {
                wordList: this.importWordList,
                bookIdList: this.selectedBookList,
                labeIdlList: this.selectedLabelList,
                langId: this.langId.langId,
                makePronunciationVoice: this.pronunciationTTSCheckbox == false ? false : true,
                makeMeanSelfVoice: this.meanSelfTTSCheckbox == false ? false : true,
                makeMeanLocalVoice: this.meanLocalTTSCheckbox == false ? false : true,
                refreshWord:this.refreshWord,
                meanLocalVoiceName:this.meanLocalVoiceName,
                meanSelfVoiceName:this.meanSelfVoiceName,
            }
            adminBathImportPresetWord(taskPackage).then(resp => {
                if (this.sendSnackbarMessage != null) this.sendSnackbarMessage(resp.msg)
                if (this.importResponseCallback != null) this.importResponseCallback(resp)
            }).finally(() => this.overlay = false)
        },
        fileParse() {
            this.importWordList = [];
            if (this.wordTextFile == null) return;
            if (this.selectedSplitFlag == null && this.selectedReplaceFlag == null)
                return;
            const reader = new FileReader();
            reader.readAsText(this.wordTextFile, "utf8");
            reader.onload = () => {
                let textContent = reader.result.trim().replaceAll("\r", "");
                if (this.selectedReplaceFlag != null) {
                    let textRows = textContent.split(this.selectedReplaceFlag.flag);
                    if (textRows != null && textRows.length > 0)
                        if (this.selectedSplitFlag != null)
                            for (let i = 0; i < textRows.length; i++)
                                this.importWordList = this.importWordList.concat(
                                    textRows[i].split(this.selectedSplitFlag.flag)
                                );
                        else this.importWordList = textRows;

                    return;
                }
                if (this.selectedSplitFlag != null)
                    this.importWordList = textContent.split(this.selectedSplitFlag.flag);
            };
        },
        inputParse() {
            this.importWordList = [];
            if (this.inputText == null) return;
            this.importWordList = this.inputText
                .replaceAll(",", "；")
                .replaceAll(";", "；")
                .replaceAll("，", "；")
                .replaceAll("、", "；")
                .replaceAll(" ", "")
                .replaceAll("\n", "；")
                .split("；");
        },
        clearProgram() {
            this.importProgram = 0;
            this.importWordList = [];
            this.selectedSplitFlag = null;
            this.selectedReplaceFlag = null;
            this.inputText = undefined;
        },
        selectFileListener(file) {
            this.wordTextFile = file;
        },
    },
};
</script>

<style scoped>
.grid-container {
    overflow: auto;
    display: grid;
    grid-template-columns: auto auto auto auto auto auto auto auto auto;
    padding: 10px;
}

.grid-item {
    padding: 5px;
    text-align: center;
}
</style>